<template>
  <div class="user-management">
    <h2 class="title1" style="margin-bottom: 20px;">
      <el-icon :size="25">
        <Setting />
      </el-icon> 权限分配
    </h2>

    <!-- 查询区域 -->
    <el-card class="box-card query-card" shadow="never" style="margin-bottom: 20px">
      <template #header>
        <div class="card-header">
          <span>操作项</span>
        </div>
      </template>
      <!-- 操作区域 -->
      <div class="action-bar">
        <span>用户名：</span>
        <el-input v-model="filters.roleId" placeholder="请输入用户名" style="width: 200px" />
        <el-button type="primary" @click="search">查询</el-button>
        <el-button type="success" plain @click="reset">重置</el-button>
        <div class="action-buttons">
          <el-button type="danger" plain @click="batchDelete">批量角色解绑</el-button>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card" shadow="never">
      <template #header>
        <div class="table-header">
          <div class="card-header">
            <span>数据列表</span>
          </div>
          <div class="action-buttons">
            <el-button type="primary" plain @click="exportToExcel">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 新增滚动容器 -->
      <div class="user-table-scroll">
        <el-table :data="userRoles" border style="width: 100%; margin-top: 20px;"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="60"></el-table-column>
          <el-table-column label="序号" align="center" width="100">
            <template #default="scope">
              {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="用户名" align="center" width="170"></el-table-column>
          <el-table-column prop="role" label="角色" align="center" width="220"></el-table-column>
          <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
          <el-table-column label="操作" align="center" width="350">
            <template #default="scope">
              <el-button type="primary" size="middle" @click="editRole(scope.row)">编辑</el-button>
              <el-button type="danger" size="middle" @click="deleteUserRole(scope.row)">角色解绑</el-button>
              <el-button type="warning" size="middle" @click="allocateMenu(scope.row)">分配菜单</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination background layout="total, sizes, prev, pager, next" :total="totalUserRoles" :page-size="pageSize"
          :current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 权限弹窗 -->
    <el-dialog v-model="dialogVisible" title="分配菜单" width="600px" top="9vh">
      <!-- 角色选择 -->
      <div>
        <el-radio-group v-model="activeRole" @change="updatePermissions">
          <el-radio-button v-for="role in roles" :key="role.roleId" :label="role.roleId">
            {{ role.roleName }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 权限列表 -->
      <div class="perm-dialog-scroll">
        <div v-for="group in permissionGroups" :key="group.group" style="margin-bottom: 32px;">
          <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px;">
            {{ group.group }}
          </div>
          <div class="perm-table-scroll">
            <el-table :data="group.list" border style="width: 100%;">
              <el-table-column prop="remark" label="权限名称" align="center"></el-table-column>
              <el-table-column label="状态" align="center">
                <template #default="scope">
                  <el-radio-group v-model="scope.row.value" @change="handlePermissionChange">
                    <el-radio-button label="有权限">有权限</el-radio-button>
                    <el-radio-button label="无权限">无权限</el-radio-button>
                  </el-radio-group>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 弹窗底部 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUserRole">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import * as XLSX from 'xlsx'

// 权限弹窗控制
const dialogVisible = ref(false)
// 当前激活的角色
const activeRole = ref('user') // 默认选中用户管理员
const activeUser = ref('user')

// 数据
const userRoles = ref([]) // 动态获取的用户角色数据
const totalUserRoles = ref(0) // 总用户角色数

// 筛选条件
const filters = reactive({
  roleId: '' // 用户名过滤条件
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)

// 查询功能
const search = () => {
  currentPage.value = 1 // 重置到第一页
  fetchUserRole()
}

// 重置功能
const reset = () => {
  filters.roleId = '' // 清空用户名过滤条件
  currentPage.value = 1 // 重置到第一页
  fetchUserRole()
}

// 分页处理
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchUserRole()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchUserRole()
}

// 批量解绑
const selectedRoles = ref([])
const handleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

const batchDelete = async () => {
  if (selectedRoles.value.length === 0) {
    ElMessage.warning('请选择要解除绑定的角色')
    return
  }
  // 批量解绑时，依次调用 deleteUserRole
  for (const user of selectedRoles.value) {
    await deleteUserRole(user)
  }
  // 解绑后刷新数据
  fetchUserRole()
}

// 编辑
const editRole = (role) => {
  ElMessage.info(`编辑角色：${role.name}`)
}

// 解除绑定
const deleteUserRole = async (user) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm(
      `确定要解绑用户 "${user.name}" 的所有角色吗？`,
      '解绑确认',
      {
        confirmButtonText: '解绑',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }
    );
    console.log(`http://localhost:8181/role/unbind/${user.id}`)
    // 调用解绑接口
    const response = await axios.get(
      `http://localhost:8181/role/unbind/${user.id}`,
      {
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      }
    );

    if (response.data.code === 200) {
      ElMessage.success(response.data.message || '解绑成功');
      fetchUserRole(); // 刷新角色数据
    } else {
      ElMessage.error(response.data.message || '解绑失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error);
      ElMessage.error('解绑请求失败，请检查后端服务');
    }
  }
}

// 修改分配菜单按钮的点击事件
const allocateMenu = (user) => {
  dialogVisible.value = true; // 显示弹窗
  activeUser.value = user.id; // 设置当前激活的用户 ID
};

// 权限列表和角色列表
const permissions = reactive([]) // 动态获取的权限列表
const roles = ref([]) // 动态获取的角色列表

// 获取角色列表
const fetchRoles = async () => {
  try {
    const response = await axios.get('http://localhost:8181/role/list', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      roles.value = response.data.data.map(role => ({
        roleId: role.roleId,
        roleName: role.roleName,
        roleKey: role.roleKey,
        remark: role.remark
      }))
    } else {
      ElMessage.error(response.data.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}
// 获取权限列表
const fetchPermissions = async () => {
  try {
    const response = await axios.get('http://localhost:8181/perm/list', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      permissions.splice(0, permissions.length, ...response.data.data.map(perm => {
        let group = '权限相关'
        if (
          perm.permKey.startsWith('emo:user:') ||
          perm.permKey.startsWith('emo:role:') ||
          perm.permKey.startsWith('emo:record:') ||
          perm.permKey === 'emo:user:role'
        ) {
          group = '用户相关'
        } else if (perm.permKey.startsWith('emo:square:')) {
          group = '广场相关'
        } else if (perm.permKey.startsWith('emo:perm:')) {
          group = '权限相关'
        }
        return {
          permId: perm.permId,
          permKey: perm.permKey,
          remark: perm.remark,
          value: '无权限',
          group
        }
      }))
    } else {
      ElMessage.error('获取权限列表失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取权限列表请求失败，请检查后端服务')
  }
}

// 更新权限列表
const updatePermissions = async () => {
  if (!activeRole.value) return

  try {
    const response = await axios.get(`http://localhost:8181/role/${activeRole.value}`, {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      const rolePermissions = response.data.data.map(perm => perm.permKey)
      permissions.forEach(perm => {
        perm.value = rolePermissions.includes(perm.permKey) ? '有权限' : '无权限'
      })
    } else {
      ElMessage.error('获取角色权限绑定失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('更新权限列表请求失败，请检查后端服务')
  }
}

// 禁止手动修改角色权限
const handlePermissionChange = () => {
  ElMessage.warning('禁止修改权限，请通过角色切换更改权限');
  updatePermissions(); // 恢复权限为角色对应的默认值
};

// 保存用户角色绑定关系
const saveUserRole = async () => {
  try {
    const userId = activeUser.value // 当前激活的用户 ID
    const roleId = activeRole.value // 当前选中的角色 ID

    if (!userId || !roleId) {
      ElMessage.warning('请选择用户和角色')
      return
    }

    const response = await axios.post(
      `http://localhost:8181/role/users/${userId}/roles/${roleId}`,
      {},
      {
        headers: {
          [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
        }
      }
    )

    if (response.data.code === 200) {
      ElMessage.success('权限保存成功')
      dialogVisible.value = false
      fetchUserRole()
    } else {
      ElMessage.error('权限保存失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 导出用户角色数据为Excel
const exportToExcel = async () => {
  try {
    // 直接调用新接口获取所有用户数据
    const response = await axios.get('http://localhost:8181/user/getUserAll', {
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })
    if (response.data.code === 200) {
      const records = response.data.data || []
      const data = [
        ['序号', '用户名', '邮箱', '角色列表'],
        ...records.map((user, idx) => [
          idx + 1,
          user.name || '',
          user.email || '',
          user.roleList ? user.roleList.map(role => role.roleName).join(', ') : '无角色'
        ])
      ]
      const worksheet = XLSX.utils.aoa_to_sheet(data)
      const workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(workbook, worksheet, '用户角色')
      XLSX.writeFile(workbook, '用户角色分配.xlsx')
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('导出失败，请检查后端服务')
  }
}

// 获取用户数据
const fetchUserRole = async () => {
  try {
    console.log(currentPage.value);
    const response = await axios.get('http://localhost:8181/role/userlist', {
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        userName: filters.roleId
      },
      headers: {
        [localStorage.getItem('tokenName')]: localStorage.getItem('tokenValue')
      }
    })

    if (response.data.code === 200) {
      const { records, total } = response.data.data

      // 映射数据
      userRoles.value = records.map(user => ({
        id: user.userId,
        name: user.name || '未填写',
        roleId: user.roleList.map(role => role.roleId),
        role: user.roleList.map(role => role.roleName).join(', ') || '无角色',
        email: user.email || '无邮箱'
      }))

      totalUserRoles.value = total
      ElMessage.success('获取用户角色数据成功')
    } else {
      ElMessage.error(response.data.message || '获取用户角色数据失败')
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('请求失败，请检查后端服务')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchUserRole()
  fetchPermissions()
  fetchRoles()
})

const permissionGroups = computed(() => {
  // 假设 permissions 里有 group 字段
  const groups = {}
  permissions.forEach(perm => {
    if (!groups[perm.group]) groups[perm.group] = []
    groups[perm.group].push(perm)
  })
  // 返回分组后的数组 [{ group: '用户相关', list: [...] }, ...]
  return Object.entries(groups).map(([group, list]) => ({ group, list }))
})
</script>

<style scoped>
.user-management {
  min-height: 100vh;
}

.box-card {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.query-card {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.action-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.title1 {
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
}

.action-buttons {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.perm-table-scroll {
  max-height: 600px;
  overflow-y: auto;
  margin-top: 10px;
}

.perm-dialog-scroll {
  max-height: 650px;
  overflow-y: auto;
  margin-top: 10px;
}

.user-table-scroll {
  max-height: 550px;
  overflow-y: auto;
  margin-top: 10px;
}
</style>